// bignumber.js用于数字精度要求较高的计算。

import BigNumber from 'bignumber.js';
BigNumber.config({
  ROUNDING_MODE: BigNumber.ROUND_DOWN, // 不进行四舍五入，直接截取,向零舍入
  EXPONENTIAL_AT: [-20, 20], // 指数计数法超过这个就用指数e表示，toNumber方法溢出浏览器还是会用指数计数法，建议改用toString方法
})
/**
 * 加法
 * @param num { number }
 * @param rest { number }
 * @return {number}
 */
export const add = (num, ...rest) => {
  if(Array.isArray(num)) {
      return BigNumber.sum.apply(null, num).toString()
  } else {
    let bn = new BigNumber(num)
    rest.forEach(item => {
        bn = new BigNumber(bn.plus(item))
    })
    return bn.toString()
  }
}

/**
 * 减法
 * @param num{ number }
 * @param rest{ number }
 * @return {number}
 */
export const subtract = (num, ...rest) => {
  let bn = new BigNumber(num)

  rest.forEach(item => {
    bn = new BigNumber(bn.minus(item))
  })
  return bn.toString()
}

/**
 * 乘法
 * @param num{ number }
 * @param rest{ number }
 * @return {number}
 */
export const multiply = (num, ...rest) => {
  let bn = new BigNumber(num)

  rest.forEach(item => {
    bn = new BigNumber(bn.multipliedBy(item))
  })
  return bn.toString()
}

/**
 * 除法
 * @param num{ number }
 * @param rest{ number }
 * @return {number}
 */
export const divide = (num, ...rest) => {
  let bn = new BigNumber(num)

  rest.forEach(item => {
    bn = new BigNumber(bn.dividedBy(item))
  })
  return bn.toString()
}

/**
 * @description: 转换成千分位
 * @param num { number | string }
 * @param precision { number }
 * @return { number }
 */
export const toFormat = ( num, config) => {
  const initConfig = {
    prefix: '',
    decimalSeparator: '.',
    groupSeparator: ',',
    groupSize: 3
}
  let bn = new BigNumber(num)
  return bn.toFormat(Object.assign(initConfig, config))
}
// 保留小数点后几位不够添0
export const toFixed = (num, precision) => {
  let bn = new BigNumber(num)
  return bn.toFixed(precision, 1)
}
// 保留几位数字
export const toPrecision = (num, precision) => {
  let bn = new BigNumber(num)
  return bn.toPrecision(precision, 1)
}

// 千分位展示
export const toThousandFilter = (value) => {
     if (!value) return ''
     const str  = value.toString()
     return str.replace(str.indexOf('.') > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g, '$1,')
}